package com.jiazhong.example.project.bookstore.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiazhong.example.project.bookstore.backend.service.DiscountService;
import com.jiazhong.example.project.bookstore.commons.bean.Discount;
import com.jiazhong.example.project.bookstore.commons.config.JwtConfig;
import com.jiazhong.example.project.bookstore.commons.handler.DiscountNotFoundException;
import com.jiazhong.example.project.bookstore.commons.handler.DiscountSaveOrUpdateException;
import com.jiazhong.example.project.bookstore.commons.mapper.DiscountMapper;
import com.jiazhong.example.project.bookstore.commons.util.JsonResult;
import com.jiazhong.example.project.bookstore.commons.util.ResultTool;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class DiscountServiceImpl extends ServiceImpl<DiscountMapper, Discount> implements DiscountService {

    @CacheEvict(cacheNames = "book_find", allEntries = true)
    public JsonResult saveOrUpdateDiscount(Discount discount, String token) {
        Claims claims = JwtConfig.parseJWT(token);
        String userId = claims.get("id").toString();
        discount.setUserId(userId);
        boolean b = saveOrUpdate(discount);
        if (!b) {
            throw new DiscountSaveOrUpdateException("添加或者修改失败");
        }
        return ResultTool.success("success");
    }

    @Override
    public JsonResult findDiscountByBookId(String bookId) {
        QueryWrapper<Discount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("book_id", bookId);
        queryWrapper.eq("status", 1);
        Discount one = getOne(queryWrapper);
        if (one == null) {
            //throw new DiscountNotFoundException("这本图书没有折扣");
            return ResultTool.fail(599, "这本图书没有折扣");
        }
        return ResultTool.success(one);
    }
}
